<template>
  <HomeNav />
  
  <div class="user-center">
    <div class="center-container">
      <!-- 左侧导航 -->
      <div class="sidebar">
        <div class="user-info">
          <el-avatar :size="80" :src="userInfo.avatar" />
          <h3>{{ userInfo.nickname }}</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="profile">
            <i class="el-icon-user"></i>
            <span>个人资料</span>
          </el-menu-item>
          <el-menu-item index="orders">
            <i class="el-icon-shopping-bag-1"></i>
            <span>我的订单</span>
          </el-menu-item>
          <el-menu-item index="favorites">
            <i class="el-icon-star-off"></i>
            <span>收藏商品</span>
          </el-menu-item>
          <el-menu-item index="coupons">
            <i class="el-icon-tickets"></i>
            <span>优惠券</span>
          </el-menu-item>
          <el-menu-item index="addresses">
            <i class="el-icon-location"></i>
            <span>收货地址</span>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 右侧内容 -->
      <div class="content">
        <!-- 个人资料 -->
        <div v-show="activeMenu === 'profile'" class="profile-section">
          <el-form :model="userInfo" label-width="100px">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
              >
                <el-avatar :size="100" :src="userInfo.avatar" />
              </el-upload>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="userInfo.nickname"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="userInfo.phone" disabled></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveProfile">保存修改</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 我的订单 -->
        <div v-show="activeMenu === 'orders'" class="orders-section">
          <el-tabs v-model="orderStatus">
            <el-tab-pane label="全部" name="all">
              <order-list :status="orderStatus" />
            </el-tab-pane>
            <el-tab-pane label="待付款" name="unpaid">
              <order-list :status="orderStatus" />
            </el-tab-pane>
            <el-tab-pane label="待发货" name="unshipped">
              <order-list :status="orderStatus" />
            </el-tab-pane>
            <el-tab-pane label="待收货" name="unreceived">
              <order-list :status="orderStatus" />
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 收藏商品 -->
        <div v-show="activeMenu === 'favorites'" class="favorites-section">
          <el-row :gutter="20">
            <el-col v-for="item in favorites" :key="item.id" :span="6">
              <div class="favorite-item">
                <img :src="item.image" :alt="item.name">
                <h4>{{ item.name }}</h4>
                <div class="price">¥{{ item.price }}</div>
                <div class="actions">
                  <el-button type="danger" size="small">取消收藏</el-button>
                  <el-button type="primary" size="small">加入购物车</el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 优惠券 -->
        <div v-show="activeMenu === 'coupons'" class="coupons-section">
          <el-tabs v-model="couponStatus">
            <el-tab-pane label="未使用" name="unused">
              <div class="coupon-list">
                <div v-for="coupon in coupons" :key="coupon.id" class="coupon-item">
                  <div class="amount">¥{{ coupon.amount }}</div>
                  <div class="info">
                    <div class="title">{{ coupon.title }}</div>
                    <div class="time">有效期至: {{ coupon.endTime }}</div>
                  </div>
                  <div class="use-btn">
                    <el-button type="danger">立即使用</el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="已使用" name="used">
              <!-- 已使用优惠券列表 -->
            </el-tab-pane>
            <el-tab-pane label="已过期" name="expired">
              <!-- 已过期优惠券列表 -->
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 收货地址 -->
        <div v-show="activeMenu === 'addresses'" class="addresses-section">
          <el-button type="primary" @click="showAddressDialog = true">新增地址</el-button>
          <div class="address-list">
            <div v-for="addr in addresses" :key="addr.id" class="address-item">
              <div class="info">
                <div class="name">{{ addr.name }} <span class="phone">{{ addr.phone }}</span></div>
                <div class="detail">{{ addr.province }}{{ addr.city }}{{ addr.district }}{{ addr.detail }}</div>
              </div>
              <div class="actions">
                <el-button type="text" @click="handleEditAddress(addr)">编辑</el-button>
                <el-button type="text" @click="deleteAddress(addr)">删除</el-button>
                <el-button v-if="!addr.isDefault" type="text" @click="setDefaultAddress(addr)">设为默认</el-button>
                <span v-else class="default-tag">默认地址</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 新增/编辑地址弹窗 -->
        <el-dialog 
          :title="isEdit ? '编辑收货地址' : '新增收货地址'" 
          v-model="showAddressDialog" 
          width="500px"
        >
          <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef">
            <el-form-item prop="name" label="收货人">
              <el-input v-model="addressForm.name" placeholder="请输入收货人姓名"></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号码">
              <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
            <el-form-item prop="region" label="所在地区">
              <el-cascader
                v-model="addressForm.region"
                :options="regionOptions"
                placeholder="请选择所在地区"
              ></el-cascader>
            </el-form-item>
            <el-form-item prop="detail" label="详细地址">
              <el-input
                type="textarea"
                v-model="addressForm.detail"
                placeholder="请输入详细地址"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showAddressDialog = false">取消</el-button>
            <el-button type="primary" @click="saveAddress">保存</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>

  <HomeFooter />
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import HomeNav from '@/components/layout/HomeNav.vue'
import HomeFooter from '@/components/layout/HomeFooter.vue'

// 用户信息
const userInfo = ref({
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  nickname: '测试用户',
  phone: '13800138000'
})

// 当前激活的菜单
const activeMenu = ref('profile')

// 订单状态
const orderStatus = ref('all')

// 优惠券状态
const couponStatus = ref('unused')

// 收藏商品数据
const favorites = ref([
  {
    id: 1,
    name: '商品1',
    image: require('@/assets/imgs/goods/goods01.png'),
    price: 199
  },
  // ...更多收藏商品
])

// 优惠券数据
const coupons = ref([
  {
    id: 1,
    amount: 50,
    title: '新人专享券',
    endTime: '2024-12-31'
  },
  // ...更多优惠券
])

// 地址数据
const addresses = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138000',
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    detail: '三里屯SOHO',
    isDefault: true
  },
  // ...更多地址
])

// 地址相关
const showAddressDialog = ref(false)
const isEdit = ref(false)
const addressFormRef = ref(null)

const addressForm = reactive({
  id: null,
  name: '',
  phone: '',
  region: [],
  detail: '',
  isDefault: false
})

// 地址验证规则
const addressRules = {
  name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  region: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  detail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 省市区数据（保持与SeckillOrderPay.vue中的数据一致）
const regionOptions = ref([
  {
    value: '110000',
    label: '北京市',
    children: [
      {
        value: '110100',
        label: '北京市',
        children: [
          { value: '110101', label: '东城区' },
          { value: '110102', label: '西城区' },
          { value: '110105', label: '朝阳区' },
          { value: '110106', label: '丰台区' },
          { value: '110107', label: '石景山区' },
          { value: '110108', label: '海淀区' },
          { value: '110109', label: '门头沟区' },
          { value: '110111', label: '房山区' },
          { value: '110112', label: '通州区' },
          { value: '110113', label: '顺义区' },
          { value: '110114', label: '昌平区' },
          { value: '110115', label: '大兴区' },
          { value: '110116', label: '怀柔区' },
          { value: '110117', label: '平谷区' },
          { value: '110228', label: '密云区' },
          { value: '110229', label: '延庆区' }
        ]
      }
    ]
  },
  {
    value: '120000',
    label: '天津市',
    children: [
      {
        value: '120100',
        label: '天津市',
        children: [
          { value: '120101', label: '和平区' },
          { value: '120102', label: '河东区' },
          { value: '120103', label: '河西区' },
          { value: '120104', label: '南开区' },
          { value: '120105', label: '河北区' },
          { value: '120106', label: '红桥区' },
          { value: '120110', label: '东丽区' },
          { value: '120111', label: '西青区' },
          { value: '120112', label: '津南区' },
          { value: '120113', label: '北辰区' },
          { value: '120114', label: '武清区' },
          { value: '120115', label: '宝坻区' },
          { value: '120116', label: '滨海新区' },
          { value: '120221', label: '宁河县' },
          { value: '120223', label: '静海县' },
          { value: '120225', label: '蓟县' }
        ]
      }
    ]
  },
  {
    value: '130000',
    label: '河北省',
    children: [
      {
        value: '130100',
        label: '石家庄市',
        children: [
          { value: '130102', label: '长安区' },
          { value: '130104', label: '桥西区' },
          { value: '130105', label: '新华区' },
          { value: '130107', label: '井陉矿区' },
          { value: '130108', label: '裕华区' },
          { value: '130109', label: '藁城区' },
          { value: '130110', label: '鹿泉区' },
          { value: '130111', label: '栾城区' },
          { value: '130121', label: '井陉县' },
          { value: '130123', label: '正定县' },
          { value: '130125', label: '行唐县' },
          { value: '130126', label: '灵寿县' },
          { value: '130127', label: '高邑县' },
          { value: '130128', label: '深泽县' },
          { value: '130129', label: '赞皇县' },
          { value: '130130', label: '无极县' },
          { value: '130131', label: '平山县' },
          { value: '130132', label: '元氏县' },
          { value: '130133', label: '赵县' },
          { value: '130181', label: '辛集市' },
          { value: '130183', label: '晋州市' },
          { value: '130184', label: '新乐市' }
        ]
      },
      {
        value: '130200',
        label: '唐山市',
        children: [
          { value: '130202', label: '路南区' },
          { value: '130203', label: '路北区' },
          { value: '130204', label: '古冶区' },
          { value: '130205', label: '开平区' },
          { value: '130207', label: '丰南区' },
          { value: '130208', label: '丰润区' },
          { value: '130209', label: '曹妃甸区' },
          { value: '130223', label: '滦县' },
          { value: '130224', label: '滦南县' },
          { value: '130225', label: '乐亭县' },
          { value: '130227', label: '迁西县' },
          { value: '130229', label: '玉田县' },
          { value: '130281', label: '遵化市' },
          { value: '130283', label: '迁安市' }
        ]
      },
      {
        value: '130300',
        label: '秦皇岛市',
        children: [
          { value: '130302', label: '海港区' },
          { value: '130303', label: '山海关区' },
          { value: '130304', label: '北戴河区' },
          { value: '130306', label: '抚宁区' },
          { value: '130321', label: '青龙满族自治县' },
          { value: '130322', label: '昌黎县' },
          { value: '130324', label: '卢龙县' }
        ]
      },
      {
        value: '130400',
        label: '邯郸市',
        children: [
          { value: '130402', label: '邯山区' },
          { value: '130403', label: '丛台区' },
          { value: '130404', label: '复兴区' },
          { value: '130406', label: '峰峰矿区' },
          { value: '130421', label: '邯郸县' },
          { value: '130423', label: '临漳县' },
          { value: '130424', label: '成安县' },
          { value: '130425', label: '大名县' },
          { value: '130426', label: '涉县' },
          { value: '130427', label: '磁县' },
          { value: '130428', label: '肥乡县' },
          { value: '130429', label: '永年县' },
          { value: '130430', label: '邱县' },
          { value: '130431', label: '鸡泽县' },
          { value: '130432', label: '广平县' },
          { value: '130433', label: '馆陶县' },
          { value: '130434', label: '魏县' },
          { value: '130435', label: '曲周县' },
          { value: '130481', label: '武安市' }
        ]
      },
      {
        value: '130500',
        label: '邢台市',
        children: [
          { value: '130502', label: '桥东区' },
          { value: '130503', label: '桥西区' },
          { value: '130521', label: '邢台县' },
          { value: '130522', label: '临城县' },
          { value: '130523', label: '内丘县' },
          { value: '130524', label: '柏乡县' },
          { value: '130525', label: '隆尧县' },
          { value: '130526', label: '任县' },
          { value: '130527', label: '南和县' },
          { value: '130528', label: '宁晋县' },
          { value: '130529', label: '巨鹿县' },
          { value: '130530', label: '新河县' },
          { value: '130531', label: '广宗县' },
          { value: '130532', label: '平乡县' },
          { value: '130533', label: '威县' },
          { value: '130534', label: '清河县' },
          { value: '130535', label: '东光县' },
          { value: '130581', label: '南宫市' },
          { value: '130582', label: '沙河市' }
        ]
      },
      {
        value: '130600',
        label: '保定市',
        children: [
          { value: '130602', label: '竞秀区' },
          { value: '130603', label: '莲池区' },
          { value: '130604', label: '满城区' },
          { value: '130606', label: '徐水区' },
          { value: '130607', label: '涞水县' },
          { value: '130608', label: '阜平县' },
          { value: '130609', label: '定兴县' },
          { value: '130610', label: '唐县' },
          { value: '130611', label: '高阳县' },
          { value: '130612', label: '容城县' },
          { value: '130613', label: '涞源县' },
          { value: '130614', label: '望都县' },
          { value: '130615', label: '安新县' },
          { value: '130616', label: '易县' },
          { value: '130617', label: '曲阳县' },
          { value: '130618', label: '蠡县' },
          { value: '130619', label: '顺平县' },
          { value: '130620', label: '博野县' },
          { value: '130621', label: '雄县' },
          { value: '130622', label: '涿州市' },
          { value: '130623', label: '定州市' },
          { value: '130624', label: '安国市' },
          { value: '130625', label: '高碑店市' }
        ]
      },
      {
        value: '130700',
        label: '张家口市',
        children: [
          { value: '130702', label: '桥东区' },
          { value: '130703', label: '桥西区' },
          { value: '130705', label: '宣化区' },
          { value: '130706', label: '下花园区' },
          { value: '130721', label: '宣化县' },
          { value: '130722', label: '张北县' },
          { value: '130723', label: '康保县' },
          { value: '130724', label: '沽源县' },
          { value: '130725', label: '尚义县' },
          { value: '130726', label: '蔚县' },
          { value: '130727', label: '阳原县' },
          { value: '130728', label: '怀安县' },
          { value: '130729', label: '万全县' },
          { value: '130730', label: '怀来县' },
          { value: '130731', label: '涿鹿县' },
          { value: '130732', label: '赤城县' },
          { value: '130733', label: '崇礼县' }
        ]
      },
      {
        value: '130800',
        label: '承德市',
        children: [
          { value: '130802', label: '双桥区' },
          { value: '130803', label: '双滦区' },
          { value: '130804', label: '鹰手营子矿区' },
          { value: '130821', label: '承德县' },
          { value: '130822', label: '兴隆县' },
          { value: '130824', label: '滦平县' },
          { value: '130825', label: '隆化县' },
          { value: '130826', label: '丰宁满族自治县' },
          { value: '130827', label: '宽城满族自治县' },
          { value: '130828', label: '围场满族蒙古族自治县' }
        ]
      },
      {
        value: '130900',
        label: '沧州市',
        children: [
          { value: '130902', label: '新华区' },
          { value: '130903', label: '运河区' },
          { value: '130921', label: '沧县' },
          { value: '130922', label: '青县' },
          { value: '130923', label: '东光县' },
          { value: '130924', label: '海兴县' },
          { value: '130925', label: '盐山县' },
          { value: '130926', label: '肃宁县' },
          { value: '130927', label: '南皮县' },
          { value: '130928', label: '吴桥县' },
          { value: '130929', label: '献县' },
          { value: '130930', label: '孟村回族自治县' },
          { value: '130981', label: '泊头市' },
          { value: '130982', label: '任丘市' },
          { value: '130983', label: '黄骅市' },
          { value: '130984', label: '河间市' }
        ]
      },
      {
        value: '131000',
        label: '廊坊市',
        children: [
          { value: '131002', label: '安次区' },
          { value: '131003', label: '广阳区' },
          { value: '131022', label: '固安县' },
          { value: '131023', label: '永清县' },
          { value: '131024', label: '香河县' },
          { value: '131025', label: '大城县' },
          { value: '131026', label: '文安县' },
          { value: '131028', label: '大厂回族自治县' },
          { value: '131081', label: '霸州市' },
          { value: '131082', label: '三河市' }
        ]
      },
      {
        value: '131100',
        label: '衡水市',
        children: [
          { value: '131102', label: '桃城区' },
          { value: '131103', label: '冀州区' },
          { value: '131121', label: '枣强县' },
          { value: '131122', label: '武邑县' },
          { value: '131123', label: '武强县' },
          { value: '131124', label: '饶阳县' },
          { value: '131125', label: '安平县' },
          { value: '131126', label: '故城县' },
          { value: '131127', label: '景县' },
          { value: '131128', label: '阜城县' },
          { value: '131181', label: '冀州市' },
          { value: '131182', label: '深州市' }
        ]
      }
    ]
  }
])

// 处理菜单选择
const handleMenuSelect = (index) => {
  activeMenu.value = index
}

// 保存个人资料
const saveProfile = () => {
  ElMessage.success('保存成功')
}

// 地址相关操作
const showAddAddressDialog = () => {
  // 显示新增地址弹窗
}

const editAddress = (addr) => {
  // 编辑地址
}

const deleteAddress = async (addr) => {
  try {
    await ElMessageBox.confirm('确定要删除该地址吗？', '提示')
    // 删除地址逻辑
    ElMessage.success('删除成功')
  } catch (error) {
    console.log('取消删除')
  }
}

const setDefaultAddress = (addr) => {
  addresses.value.forEach(item => item.isDefault = false)
  addr.isDefault = true
  ElMessage.success('设置成功')
}

// 编辑地址
const handleEditAddress = (addr) => {
  isEdit.value = true
  addressForm.id = addr.id
  addressForm.name = addr.name
  addressForm.phone = addr.phone
  addressForm.detail = addr.detail
  addressForm.isDefault = addr.isDefault
  
  // 根据地址信息反查region的值
  const findRegionCode = (label, level = 0, options = regionOptions.value) => {
    for (const option of options) {
      if (option.label === label) {
        return option.value
      }
      if (option.children && level < 2) {
        const found = findRegionCode(label, level + 1, option.children)
        if (found) return found
      }
    }
    return null
  }

  addressForm.region = [
    findRegionCode(addr.province),
    findRegionCode(addr.city),
    findRegionCode(addr.district)
  ]
  
  showAddressDialog.value = true
}

// 保存地址
const saveAddress = async () => {
  if (!addressFormRef.value) return
  
  try {
    await addressFormRef.value.validate()
    
    // 获取省市区名称
    const getRegionLabel = (code) => {
      const findLabel = (code, options = regionOptions.value) => {
        for (const option of options) {
          if (option.value === code) return option.label
          if (option.children) {
            const found = findLabel(code, option.children)
            if (found) return found
          }
        }
        return ''
      }
      return findLabel(code)
    }

    const address = {
      id: addressForm.id || addresses.value.length + 1,
      name: addressForm.name,
      phone: addressForm.phone,
      province: getRegionLabel(addressForm.region[0]),
      city: getRegionLabel(addressForm.region[1]),
      district: getRegionLabel(addressForm.region[2]),
      detail: addressForm.detail,
      isDefault: addressForm.isDefault
    }

    if (addressForm.isDefault) {
      addresses.value.forEach(addr => addr.isDefault = false)
    }

    if (isEdit.value) {
      const index = addresses.value.findIndex(addr => addr.id === address.id)
      if (index !== -1) {
        addresses.value[index] = address
      }
      ElMessage.success('地址修改成功')
    } else {
      addresses.value.push(address)
      ElMessage.success('地址添加成功')
    }

    showAddressDialog.value = false
    resetAddressForm()
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 重置地址表单
const resetAddressForm = () => {
  addressForm.id = null
  addressForm.name = ''
  addressForm.phone = ''
  addressForm.region = []
  addressForm.detail = ''
  addressForm.isDefault = false
  isEdit.value = false
  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }
}
</script>

<style lang="scss" scoped>
.user-center {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 20px 0;

  .center-container {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    gap: 20px;

    .sidebar {
      width: 240px;
      background: #fff;
      border-radius: 8px;
      padding: 20px 0;

      .user-info {
        text-align: center;
        padding: 20px;
        border-bottom: 1px solid #f0f0f0;

        h3 {
          margin: 10px 0;
          color: #333;
        }
      }
    }

    .content {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      padding: 20px;

      // 收藏商品样式
      .favorite-item {
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        padding: 10px;
        text-align: center;

        img {
          width: 100%;
          height: 200px;
          object-fit: cover;
        }

        h4 {
          margin: 10px 0;
          font-size: 14px;
        }

        .price {
          color: #ff4d4f;
          font-weight: bold;
          margin-bottom: 10px;
        }

        .actions {
          display: flex;
          justify-content: space-around;
        }
      }

      // 优惠券样式
      .coupon-item {
        display: flex;
        align-items: center;
        background: #fff5f5;
        border-radius: 4px;
        margin-bottom: 15px;
        padding: 20px;

        .amount {
          font-size: 24px;
          color: #ff4d4f;
          font-weight: bold;
          margin-right: 20px;
        }

        .info {
          flex: 1;

          .title {
            font-size: 16px;
            margin-bottom: 5px;
          }

          .time {
            color: #999;
            font-size: 12px;
          }
        }
      }

      // 地址列表样式
      .address-item {
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .info {
          .name {
            font-size: 16px;
            margin-bottom: 5px;

            .phone {
              color: #666;
              margin-left: 10px;
            }
          }

          .detail {
            color: #666;
          }
        }

        .actions {
          .el-button {
            margin-left: 10px;
          }

          .default-tag {
            background: #ff4d4f;
            color: #fff;
            padding: 2px 6px;
            border-radius: 2px;
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
